/**
 * 
 */
package fr.utbm.gi.in56.database;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

/**
 * Abstract implementation of a database manager.
 *
 * @author Adrien Hoffer & Tarik Belabbas
 *
 */
public abstract class DatabaseManager
{
	/**
	 * The connection to the database. 
	 */
	private Connection connection;
	
	/**
	 * The statement used for database queries
	 */
	private List< Statement > statements;
	
	/**
	 * Parameterized constructor.
	 * 
	 * @param _connection the connection to use to create a statement
	 * @throws SQLException if the connection cannot create a statement
	 */
	public DatabaseManager( Connection _connection )
	{
		this.connection = _connection;
	}
	
	/**
	 * Creates and returns a new statement.
	 * 
	 * @return the statement created
	 */
	protected Statement getNewStatement() 
	{
		Statement statement = null;
		
		try
		{
			// TYPE_FORWARD_ONLY: read the statement from top to bottom
	        // CONCUR_UPDATABLE: it's possible to modify the datas from the statement
			statement = this.connection.createStatement( ResultSet.TYPE_FORWARD_ONLY,
				ResultSet.CONCUR_UPDATABLE );
		}
		catch ( SQLException _exception )
		{
			System.out.println( "SQLException" ); //$NON-NLS-1$
		}
		
		return statement;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#finalize()
	 */
	@Override
	protected void finalize() throws Throwable
	{
		try
		{
			for ( Statement currentStatement : statements )
			{
				currentStatement.close();
			}
		}
		finally
		{
			super.finalize();
		}
	}
	
	/**
	 * Returns the connection
	 * 
	 * @return the connection
	 */
	protected Connection getConnection()
	{
		return this.connection;
	}
}
